package cn.com.manager.dao.weibo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.DefaultSortParameters;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Repository;

import cn.com.manager.utility.ApplicationConstants;

@Repository(value = "postDao")
public class PostDao extends RedisBase {
	private static final String TABLE_NAME = "post:";

	private Long getPrimaryKey() {
		return super.getPrimaryKey("global:postid");
	}

	/**
	 * 保存微博信息
	 * 
	 * @param uid
	 * @param username
	 * @param time
	 * @param content
	 */
	public String postSave(String uid, String username, String time, String content) {
		Map<String, Object> postInfo = new HashMap<String, Object>();
		// 用户id
		postInfo.put("userid", uid);
		postInfo.put("username", username);
		postInfo.put("time", time);
		postInfo.put("content", content);

		String postid = String.valueOf(this.getPrimaryKey());
		super.hashAdd(TABLE_NAME + "postid:" + postid, postInfo);
		return postid;
	}

	/**
	 * 用户最近发微博保存
	 * 供粉丝获取
	 * @param uid
	 * @param postid
	 */
	public void recentPostSave(String uid, String postid) {
		stringRedisTemplate.opsForZSet().add("startpost:userid" + uid, postid, Double.parseDouble(postid));
		// 只保存用户最近20条微博
		if (super.ZSetLen("startpost:userid" + uid) > ApplicationConstants.weibo_show_recent_post_amount) {
			stringRedisTemplate.opsForZSet().removeRange("startpost:userid" + uid, 0, 0);
		}
	}
	
	/**
	 * 
	 * @param uid
	 * @param postid
	 */
	public void saveOldPost(String uid,String postid){
		stringRedisTemplate.opsForList().leftPush("mypost:userid:"+uid, postid);
		if(super.keyLen("mypost:userid:"+uid) > ApplicationConstants.weibo_redis_post_amount){
			stringRedisTemplate.opsForList().rightPopAndLeftPush("mypost:userid:"+uid, "global:store");
		}
	}
	
	public Map<String,Object> getoldPost(){
		String postId = stringRedisTemplate.opsForList().rightPop("global:store");
		Map<String,Object> postInfo = null;
		if(StringUtils.isNoneBlank(postId)){
			postInfo = new HashMap<String, Object>();
			String userId = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "userid");
			String username = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "username");
			String content = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "content");
			String time = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "time");
			postInfo.put("postId", postId);
			postInfo.put("userId", userId);
			postInfo.put("username", username);
			postInfo.put("content", content);
			postInfo.put("time", Long.parseLong(time));
		}
		return postInfo;
	}

	/**
	 * 获取用户发的微博
	 * 
	 * @param uid
	 * @param min
	 * @return
	 */
	public List<String> getPostIdByUserId(String uid, Double min) {
		Set result = stringRedisTemplate.opsForZSet().rangeByScore("startpost:userid" + uid, min, Double.MAX_VALUE);
		if(result == null){
			return null;
		}
		return new ArrayList<String>(result);
	}

	/**
	 * 保存本次用户的最大微博id
	 * 
	 * @param userid
	 * @param postid
	 */
	public void setLastPostIdByUserId(String userid, String postid) {
		stringRedisTemplate.opsForValue().set("lastpull:userid:" + userid + ":postid", postid);
	}

	/**
	 * 根据用户id获取上次发微博的id
	 * 
	 * @param userid
	 * @return
	 */
	public Double getLastPostIdByUserId(String userid) {
		String lastPostId = stringRedisTemplate.opsForValue().get("lastpull:userid:" + userid + ":postid");
		return lastPostId == null ? null :Double.parseDouble((String)lastPostId );
	}

	/**
	 * 放入收取列表
	 * 
	 * @param userid
	 * @param postid
	 */
	public void saveReceivePostId(String userid, String postid) {
		stringRedisTemplate.opsForList().leftPush("receivepost:userid:" + userid, postid);
	}

	/**
	 * 获取微博
	 * @param userid
	 * @return
	 */
	public List<Map<String, Object>> getReceivePost(String userid) {
		List<byte[]> postIdsOfBytes = stringRedisTemplate.execute(new RedisCallback<List<byte[]>>() {

			@Override
			public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
				DefaultSortParameters sortParam = new DefaultSortParameters();
				sortParam.setOrder(Order.DESC);
				List<byte[]> sort = connection.sort(
						stringRedisTemplate.getStringSerializer().serialize("receivepost:userid:" + userid), sortParam);
				return sort;
			}

		});
		List<Map<String, Object>> postInfos = new ArrayList<Map<String, Object>>();
		Map<String, Object> postInfo = null;
		for (byte[] postIdOfBytes : postIdsOfBytes) {
			postInfo = new HashMap<String, Object>();
			String postId = stringRedisTemplate.getStringSerializer().deserialize(postIdOfBytes);
			String userId = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "userid");
			String username = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "username");
			String content = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "content");
			String time = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "time");
			postInfo.put("postId", postId);
			postInfo.put("userId", userId);
			postInfo.put("username", username);
			postInfo.put("content", content);
			postInfo.put("time", System.currentTimeMillis()-Long.parseLong(time));
			postInfos.add(postInfo);
		}
		return postInfos;
	}
	
	public void saveRecentPost(String postid){
		stringRedisTemplate.opsForList().leftPush("recentPost:postid",postid);
		if(super.keyLen("recentPost:postid") > ApplicationConstants.weibo_recent_post_amount){
			stringRedisTemplate.opsForList().rightPop("recentPost:postid");
		}
	}
	
	public List<Map<String, Object>> getRecentPost(){
		List<String> postIds = stringRedisTemplate.opsForList().range("recentPost:postid", 0, -1);
		List<Map<String, Object>> postInfos = new ArrayList<Map<String, Object>>();
		Map<String, Object> postInfo = null;
		for (String postId : postIds) {
			postInfo = new HashMap<String, Object>();
			String userId = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "userid");
			String username = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "username");
			String content = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "content");
			String time = (String) stringRedisTemplate.opsForHash().get(TABLE_NAME + "postid:" + postId, "time");
			postInfo.put("postId", postId);
			postInfo.put("userId", userId);
			postInfo.put("username", username);
			postInfo.put("content", content);
			postInfo.put("time", System.currentTimeMillis()-Long.parseLong(time));
			postInfos.add(postInfo);
		}
		return postInfos;
	}
}
